import { defineStore } from 'pinia';
import { login, reg } from '../api';
import axios from 'axios';

export const useAuthStore = defineStore('auth', {
  state: () => ({
    user: null,
    token: localStorage.getItem('token') || null
  }),
  actions: {
    // src/stores/auth.js
async loginUser(credentials) {
  try {
    const response = await axios.post('/api/demo/login', {
      username: credentials.username,
      pwd: credentials.password // 确保字段名与后端一致
    });
    
    // 根据后端实际返回结构调整
    if (response.data.errno === 0) {
      this.user = response.data.data.user;
      this.token = response.data.data.token;
      localStorage.setItem('token', this.token);
      return true;
    } else {
      console.error('登录失败:', response.data.message);
      throw new Error(response.data.message); // 抛出错误以便捕获
    }
  } catch (error) {
    console.error('登录请求错误:', error);
    throw error; // 继续抛出错误
  }
},
   async registerUser(userData) {
  try {
    const response = await axios.post('/api/demo/reg', {
      // 确保字段名与后端一致
      stuNum: userData.stuNum,
      username: userData.username,
      pwd: userData.pwd,
      age: userData.age,
      realName: userData.realName,
      email: userData.email,
      className: userData.className
    });
    
    // 根据后端实际返回结构调整
    if (response.data.errno === 0 || response.data.affectedRows === 1) {
      return response.data;
    } else {
      throw new Error(response.data.message || '注册失败');
    }
  } catch (error) {
    console.error('注册错误:', error);
    throw error;
  }
},
    logout() {
      this.user = null;
      this.token = null;
      localStorage.removeItem('token');
    }
  }
});